const router = require('koa-router')()
// let fs = require( "fs");
// let path = require( "path");
const child_process = require('child_process')
const kill =  require('tree-kill')
const serverIp = "192.168.50.98"
let handleList = {}
let rtspList = new Map()

router.post('/startStream', async (ctx, next) => {
  let body = ctx.request.body
  if (body.url) {
    if (rtspList.has(body.url)) {
      rtspList.get(body.url).num += 1
      ctx.body = {
        status: 0,
        msg: "启动流转换服务成功!",
        dataMap: {
          timeId: rtspList.get(body.url).t,
          url: rtspList.get(body.url).rtmp,
          ip: ''
        }
      }
      ctx.status = 200
      return
    }
    let t = 'mystream' || new Date().getTime() + (Math.random() * 1000 | 1)
    let rtmp = `rtmp://${serverIp}:1935/hls/${t}`
    let handle = child_process.exec(`ffmpeg -i "${body.url}" -f flv -r 25 -s 1920*1080 -an "${rtmp}"`, { cwd: __dirname })

    

    handleList[t] = body.url
    rtspList.set(body.url, {
      num: 1,
      t, handle, rtmp,
      lastTime: t
    })
    handle.stdout.on('data', (data) => {
      console.log('info', data)
    })
  
    handle.stderr.on('data', (data) => {
      // console.log(t + ' warn:', data)
    })

    ctx.body = {
      status: 0,
      msg: "启动流转换服务成功!",
      dataMap: {
        timeId: t,
        url: rtmp,
        ip: ''
      }
    }
    ctx.status = 200
  } else {
    ctx.throw(200, { message: 'url不能为空！' })
  }


})

router.post('/shutdownStream', async (ctx, next) => {
  let data = ctx.request.body
  if (data.timeId && handleList[data.timeId]) {
    let url = handleList[data.timeId]
    rtspList.get(url).num -= 1
    if (rtspList.get(url).num === 0) {
      kill(rtspList.get(url).handle.pid)
      delete handleList[data.timeId]
      rtspList.delete(url)
    }
    ctx.body = '关闭流转换服务成功！'
    ctx.status = 200
    
  } else {
    ctx.throw(200, { message: 'error' })
  }

})

// heartbeat

router.post('/heartbeat', async (ctx, next) => {

  let data = ctx.request.body
  if (data.timeId && handleList[data.timeId]) {
    let url = handleList[data.timeId]
    rtspList.get(url).lastTime = new Date().getTime()
    ctx.body = '心跳更新成功！'
    ctx.status = 200
  } else {
    ctx.body = '心跳更新失败！'
    ctx.status = 200
  }
  
})

const getOpenLog = () => {
  console.log('------------------------------------openLog-------------------------------------')
  rtspList.forEach((item, key) => {
    console.log(`${key}---${item.num}`)
  })
  console.log('--------------------------------------End---------------------------------------')
}


let nowTime = ''
let kills = []
setInterval(() => {
  try {
    nowTime = new Date().getTime()
    kills.length = 0
    rtspList.forEach((item, key) => {
      if (nowTime - item.lastTime > 0.8 * 60 * 1000) {
        kills.push({item, key})
      }
    })
    kills.length && kills.forEach(({item, key})=>{
      kill(item.handle.pid)
      delete handleList[item.t]
      rtspList.delete(key)
    })
    getOpenLog()
  } catch (error) {
    console.log(error)
  }
}, 0.5 * 60 * 1000);

// tasklist /FI "IMAGENAME eq ffmpeg.exe"

module.exports = router